# _*_ coding: utf-8 _*_
# @Author   : Wei Yue
# @Time     : 2024-09-05 16:17
# @Function :
from datetime import datetime
from docx.shared import RGBColor
import requests
from docx import Document
from docx.shared import Inches
from io import BytesIO
from PIL import Image
from automotiveNews.common.constant import HEADERS, IMAGES_LIMIT
from automotiveNews.common.utils import set_font, generate_number, add_hyperlink
import tempfile
import os
from collections import defaultdict


class MyDocument:
    def __init__(self, articles: list):
        self.articles = articles
        self.doc = Document()

    def add_images_in_row(self, paragraph, image_urls, width=Inches(1.96)):
        image_count = 0
        for url in image_urls:
            if image_count >= IMAGES_LIMIT:  # 检查是否已达到图片数量限制
                break  # 如果是，则退出循环
            try:
                response = requests.get(url, headers=HEADERS)
                if response.status_code == 200:
                    with tempfile.NamedTemporaryFile(delete=False, suffix='.jpg') as tmp_image:
                        image = Image.open(BytesIO(response.content))
                        image.convert('RGB').save(tmp_image.name, 'JPEG')
                        run = paragraph.add_run()
                        run.add_picture(tmp_image.name, width=width)
                        tmp_image.close()  # 确保文件被关闭
                        # 删除临时文件
                        os.unlink(tmp_image.name)
                        image_count += 1  # 增加计数器
            except Exception as e:
                print(f"下载图片时出现错误：{e}, 跳过图片：{url}")
            # 添加一个软换行符，以便在同一行内继续添加图片
            paragraph.add_run('\u00A0')  # Unicode NO-BREAK SPACE

    def generate_docs(self):
        print('开始生成文档，请耐心等待...')
        articles_by_topic = defaultdict(list)
        for article in self.articles:
            articles_by_topic[article.topic].append(article)
        for topic, articles in articles_by_topic.items():
            first_heading = self.doc.add_heading(topic.value, level=1)
            set_font(first_heading, '黑体', 16, True)
            for article in articles:
                print(f'文章【{article.title}】导出中...')
                # 添加标题
                second_heading = self.doc.add_heading(article.title, level=2)
                set_font(second_heading, '楷体', 14)
                title_para_str = f'来源：【{article.source}】，链接：{article.url}，日期：{article.date}'
                if article.keyword:
                    title_para_str += f'，关键字：{article.keyword}'
                title_para = self.doc.add_paragraph(title_para_str)
                set_font(title_para, '微软雅黑', 7)
                # 创建一个新的段落来添加图片
                paragraph = self.doc.add_paragraph()
                self.add_images_in_row(paragraph, article.article_detail.image_urls)
                content_para = self.doc.add_paragraph(article.article_detail.content)
                set_font(content_para, '仿宋', 12)
                read_more_para = self.doc.add_paragraph()
                add_hyperlink(read_more_para, '阅读更多', article.url)
                set_font(read_more_para, '仿宋', 12)
        current_year = datetime.now().year
        title = f"【{current_year}年第{generate_number()}期】"
        self.doc.save(f'download/{title}【共{len(self.articles)}篇】.docx')
        print(f'{title}【共{len(self.articles)}篇】报告生成完毕...')
